package com.chenggcode.security.jwt.service.impl;

import com.chenggcode.security.jwt.entity.UserInfo;
import com.chenggcode.security.jwt.repository.UserInfoRepository;
import com.chenggcode.security.jwt.service.UserInfoService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @author Chenggcode
 * @date 2025/7/7 15:31
 */
@Service
@RequiredArgsConstructor
public class UserInfoServiceImpl implements UserDetailsService, UserInfoService {
    private final PasswordEncoder passwordEncoder;
    private final UserInfoRepository userInfoRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Optional<UserInfo> userInfo = userInfoRepository.findByUsername(username);
        if (userInfo.isEmpty()) {
            throw new UsernameNotFoundException("User not found with username: " + username);
        }
        return new UserInfoDetails(userInfo.get());
    }

    @Override
    public void addUser(UserInfo userInfo) {
        userInfoRepository.findByUsername(userInfo.getUsername()).ifPresent(existingUser -> {
            throw new IllegalArgumentException("User with username " + userInfo.getUsername() + " already exists.");
        });
        userInfo.setPassword(passwordEncoder.encode(userInfo.getPassword()));
        userInfoRepository.save(userInfo);
    }
}
